import { PageProps } from "@/interfaces/app.interface"
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { ModalCustom } from "@/components/modal/modal.context"
import ListTable from "@/components/utils/list.table"
import eventBus from "@/utils/event.bus"
import { ColumnType } from "antd/es/table/interface"
import { Button, Row, Col, Space, Popconfirm, message, Modal, Form, Input, Select, DatePicker } from "antd"
import serviceData from "@/services/service.data"
import { returnColumnFields } from "@/utils/column.fields"
import AddProduct from "@/components/modal/data/addProductInfo.modal.tsx"
import ProbatchUpload from "@/components/modal/data/probatchUpload.modal"
import UpdateProduct from "@/components/modal/data/updateProductInfo.modal"

import { useForm } from "antd/lib/form/Form"
import "./tradeData.less"
import moment from "moment"
import { proClassData } from "@/interfaces/api.interface"
import { deleteTradesParams } from "@/interfaces/params.interface"

const { Option } = Select
const { RangePicker } = DatePicker

const productData = (props: PageProps) => {
	const [params, setParams] = useState({})
	const withParams = useRef<any>()
	useEffect(() => {
		withParams.current = params
	}, [params])
	const [selectItem, setSelectItem] = useState<{ [key: number]: any[] }>({})
	const selectChange = useCallback(
		(selectedRowKeys: React.ReactText[], selectedRows: any[]) => {
			console.log(selectedRowKeys)
			let dataLength = 0
			const hasData = { ...selectItem }
			hasData[pageIndex.current] = selectedRows
			Object.values(hasData).forEach(m => {
				dataLength = dataLength + m.length
			})
			// if (!(dataLength > 9)) {
			// 	const hasData = { ...selectItem }
			hasData[pageIndex.current] = selectedRows
			setSelectItem(hasData)
			// } else {
			// 	message.info("产品数据最多选择10个")
			// }
		},
		[selectItem]
	)
	const needData = useRef<any[]>([])
	const pageIndex = useRef(1)
	const exportIndex = useCallback((index: number) => {
		pageIndex.current = index
	}, [])
	const selectKeys = useMemo(() => {
		needData.current = []
		Object.values(selectItem).forEach(m => {
			needData.current = needData.current.concat(m)
		})
		return needData.current.map(m => m.id)
	}, [selectItem])

	const columns: ColumnType<any>[] = [
		{
			title: "操作",
			dataIndex: "id",
			key: "options",
			fixed: "right",
			width: 160,
			align: "center",
			render: (v: any, item: any) => {
				return (
					<Space size={10}>
						<Button
							size="middle"
							type="primary"
							onClick={handleUpdate(item.id, item)}
							style={{ backgroundColor: "#05B7B7" }}
						>
							编辑
						</Button>
						<Button size="middle" type="primary" onClick={putAway(item.id)}>
							上架
						</Button>
						<Button size="middle" type="primary" onClick={downAway(item.id, "down")}>
							下架
						</Button>
						<Button size="middle" type="primary" danger onClick={downAway(item.id, "delete")}>
							删除
						</Button>
					</Space>
				)
			}
		}
	]
	// 新增产品信息
	const handleAdd = (id: string) => () => {
		ModalCustom({
			content: AddProduct,
			params: {
				id
			}
		})
	}
	// 编辑产品信息
	const handleUpdate = (id: string, item: {}) => () => {
		ModalCustom({
			content: UpdateProduct,
			params: {
				id,
				item
			}
		})
	}

	// 批量删除
	const allDelete = useCallback(
		(type: string) => () => {
			let data: any[] = []
			Object.values(needData.current).forEach(m => {
				data = data.concat(m)
			})
			console.log(data)
			let params = data.map(m => m.id)

			if (data.length == 0) {
				Modal.confirm({
					title: "请至少勾选一条数据",
					onOk: () => {
						Modal.destroyAll()
					}
				})
			} else {
				Modal.confirm({
					title: type == "delete" ? "批量删除产品数据" : "批量下架产品数据",
					content: "delete" ? "是否删除所有勾选产品数据？" : "是否下架所有勾选产品数据？",
					closable: true,
					onOk: () => {
						handleDownOrDel(params, type)
					}
				})
			}
		},
		[selectItem]
	)

	// 批量上架
	const allPutaway = useCallback(() => {
		let data: any[] = []
		Object.values(needData.current).forEach(m => {
			data = data.concat(m)
		})
		console.log(data)
		let params = data.map(m => m.id)
		if (data.length == 0) {
			Modal.confirm({
				title: "请至少勾选一条数据",
				onOk: () => {
					Modal.destroyAll()
				}
			})
		} else {
			Modal.confirm({
				title: "批量上架产品数据",
				content: "是否上架所有勾选产品数据？",
				closable: true,
				onOk: () => {
					upProductDatas(params)
				}
			})
		}
	}, [selectItem])
	const upProductDatas = (params: deleteTradesParams) => {
		serviceData.upProductDatas(params).then(res => {
			if (res.code === 200) {
				message.success("产品已成功上架")
				eventBus.emit("doProductData")
				setSelectItem({})
				Modal.destroyAll()
			}
		})
	}

	const handleDownOrDel = (params: deleteTradesParams, key: string) => {
		serviceData[key == "down" ? "downProductDatas" : "deleteProductDatas"](params).then(res => {
			if (res.code === 200) {
				if (key == "down") {
					message.success("产品已成功下架")
				} else {
					message.success("产品数据已成功删除")
				}
				eventBus.emit("doProductData")
				setSelectItem({})
				Modal.destroyAll()
			}
		})
	}
	// 批量上传
	const allApload = () => {
		console.log("批量上传")
		ModalCustom({
			content: ProbatchUpload
		})
	}

	// 单个上架
	const putAway = (id: number) => () => {
		Modal.confirm({
			title: "上架该产品数据",
			content: "是否上架该产品数据？",
			closable: true,
			onOk: () => {
				upProductDatas([id])
			}
		})
	}
	// 单个下架
	const downAway = (id: number, type: string) => () => {
		Modal.confirm({
			title: type == "down" ? "下架该产品数据" : "删除该产品数据",
			content: "down" ? "是否下架该产品数据？" : "是否删除该产品数据？",
			closable: true,
			onOk: () => {
				handleDownOrDel([id], type)
			}
		})
	}
	// 抛出事件
	useEffect(() => {
		eventBus.on("doProductData", () => setParams({ ...withParams.current }))
		return () => {
			eventBus.off("doProductData")
		}
	}, [])
	const titleRender = useCallback(
		() => (
			<Row justify="space-between" align="middle">
				<Col></Col>
				<Col>
					<Space>
						<Button type="primary" onClick={allDelete("delete")}>
							批量删除
						</Button>
						<Button type="primary" onClick={allPutaway}>
							批量上架
						</Button>
						<Button type="primary" onClick={allDelete("down")}>
							批量下架
						</Button>
						<Button type="primary" onClick={allApload}>
							批量上传
						</Button>
						<Button type="primary" onClick={handleAdd("")}>
							新增产品
						</Button>
					</Space>
				</Col>
			</Row>
		),
		[]
	)
	const [form] = useForm()
	// 搜索
	const onFinish = (values: { startTime: string; endTime: string; time: [string, string] }) => {
		if (!!values.time) {
			values.startTime = moment(new Date(values["time"][0])).format("YYYY-MM-DD")
			values.endTime = moment(new Date(values["time"][1])).format("YYYY-MM-DD")
			delete values.time
		}
		setParams(values)
	}
	// 点击重置按钮 参数为空
	const toResethandle = () => {
		setParams({})
		form.setFields([
			{
				name: "key",
				value: ""
			},
			{
				name: "industryId",
				value: ""
			},
			{
				name: "solutionId",
				value: ""
			},
			{
				name: "status",
				value: ""
			},
			{
				name: "time",
				value: ""
			}
		])
	}
	const [productClassOne, setProductClassOne] = useState<proClassData[]>([])
	const [productClassTwo, setProductClassTwo] = useState([])
	// 初始加载获取一级分类
	useEffect(() => {
		serviceData.getProductClass({ pid: 0 }).then(res => {
			setProductClassOne(res.data)
		})
	}, [])
	// 改变一级分类加载二级分类
	const onValuesChange = useCallback((changedValues: any, values: any) => {
		console.log(changedValues)
		if ("industryId" in changedValues) {
			serviceData.getProductClass({ pid: changedValues.industryId }).then(res => {
				setProductClassTwo(res.data)
			})
		}
		if ("time" in changedValues) {
			console.log(params)
		}
	}, [])
	useEffect(() => {
		form.setFields([
			{
				name: "solutionId",
				value: ""
			}
		])
	}, [productClassTwo])
	return (
		<Row className="data-form full">
			<Col className="form-search" span={24}>
				<Form form={form} onFinish={onFinish} onValuesChange={onValuesChange}>
					<Form.Item name="key" label="关键字" style={{ display: "inline-flex", width: "calc(20% - 4px)" }}>
						<Input placeholder={"请输入产品名称/订货型号"} maxLength={20} />
					</Form.Item>
					<Form.Item
						name="firstCategoryId"
						label="产品分类"
						style={{ display: "inline-flex", width: "calc(20% - 4px)", marginLeft: 20 }}
					>
						<Select placeholder={"一级分类"}>
							{productClassOne.map(item => (
								<Option key={item.id} value={item.id}>
									{item.title}
								</Option>
							))}
						</Select>
					</Form.Item>
					{/* <Form.Item name="solutionId" style={{ display: "inline-flex", width: "calc(20% - 4px)", marginLeft: 10 }}>
						<Select placeholder={"二级分类"}>
							{tradeClassTwo.map(item => (
								<Option key={item.id} value={item.id}>
									{item.title}
								</Option>
							))}
						</Select>
					</Form.Item> */}
					<Form.Item
						name="status"
						label={"状态"}
						style={{ display: "inline-flex", width: "calc(20% - 4px)", marginLeft: 20 }}
					>
						{/* tradeClassTwo */}
						<Select placeholder={"状态"}>
							<Option key={-1} value={-1}>
								{"待上架"}
							</Option>
							<Option key={0} value={0}>
								{"已下架"}
							</Option>
							<Option key={1} value={1}>
								{"已上架"}
							</Option>
						</Select>
					</Form.Item>
					<Form.Item
						name="time"
						label={"创建时间"}
						style={{ display: "inline-flex", width: "calc(20% - 4px)", marginLeft: 20 }}
					>
						<RangePicker />
					</Form.Item>
					<Form.Item style={{ display: "inline-flex", marginLeft: 20 }}>
						<Button className="colorBtn" htmlType="submit" style={{ marginLeft: 20 }}>
							<span style={{ margin: "0 auto" }}>搜索</span>
						</Button>
					</Form.Item>

					<Button onClick={toResethandle} style={{ display: "inline-flex", marginLeft: 20 }}>
						<span style={{ margin: "0 auto" }}>重置</span>
					</Button>
				</Form>
			</Col>
			<Col className="form-result" span={24}>
				<ListTable
					exportIndex={exportIndex}
					title={titleRender}
					searchParams={params}
					columns={returnColumnFields([
						"sort",
						"productName",
						"productModel",
						"productType",
						"dataStatus",
						"creatorName",
						"createDate"
					]).concat(columns)}
					//正式使用补充相关的数据接口,直接传引用就行,相关的参数(包含分页参数)会自动传入接口调用中.
					apiService={serviceData.getProductData}
					// dataSource={dataSource}
					rowSelection={{
						selectedRowKeys: selectKeys,
						onChange: selectChange
					}}
				/>
			</Col>
		</Row>
	)
}
productData.title = "产品数据"
export default productData
